import router from '@/router/index';
import { LOCALSTORAGE_TOKEN, LOCALSTORAGE_USERINFO, LOCALSTORAGE_PERMISSIONS } from '@/config';

import StorageService from '@/services/storage';
import { useAppStore } from '@/stores/app';
import { useUserStore } from '@/stores/user';
import { useAuthStore } from '@/stores/auth';
import { oauthUserInfo } from '@/api/oauth.js';

import { ElMessage } from 'element-plus';

// token
export const setToken = (token: string) => {
  useAuthStore().setToken(token);
  StorageService.setLocal(LOCALSTORAGE_TOKEN, token);
};
export const getToken = (token: string) => {
  return useAuthStore().token; // StorageService.getLocal(LOCALSTORAGE_TOKEN, token);
};
export const removeToken = () => {
  useAuthStore().setToken('');
  StorageService.removeLocal(LOCALSTORAGE_TOKEN);
};

// 登录、退出
export const appLogin = (token: string) => {
  appLoginHandler(token);
};
// 登录后逻辑
export const appLoginHandler = async (token: string) => {
  setToken(token);
  await getUserinfo();
  router.push('/');
};

// 退出操作
export const appLoginOut = () => {
  appLoginOutHandler();
};
// 退出后逻辑
export const appLoginOutHandler = () => {
  const appStore = useAppStore();
  appStore.setDynamicRoutes([]); // 清除动态路由
  appStore.setDynamicRoutesState(false); // 清除动态路由加载状态
  removeToken();
  removeUser();
  removePermissions();
  // router.push({ name: 'Login' });
  // 重置路由信息: 可以重置addRoutes的数据
  location.href = '/#/login';
};

// 用户信息、权限

export const setUser = (userinfo: any) => {
  const userStore = useUserStore();
  userStore.setUser(userinfo);
  StorageService.setLocal(LOCALSTORAGE_USERINFO, userinfo);
};
export const removeUser = () => {
  setUser(null);
};

export const getUserinfo = async () => {
  // 获取用户信息
  const { err, data } = await oauthUserInfo();
  if (err) return;

  const { is_admin, role_id, is_frozen } = data;
  if ((is_admin === 0 && role_id <= 0) || is_frozen) {
    ElMessage.error('暂无权限，请联系管理员开通!');
    appLoginOutHandler();
    return;
  } else {
    setPermissions(data.permissions);
    setUser(data);
  }
};

export const setPermissions = (permissions: any[]) => {
  useAuthStore().setPermissions(permissions);
  StorageService.setLocal(LOCALSTORAGE_PERMISSIONS, permissions);
};
export const removePermissions = () => {
  setPermissions([]);
};
/** 获取权限code集合 */
export const getPermissions = () => useAuthStore().permissionsMap ?? {};

